package com.tengju.bff.interfaces.covercharge.util.alarmUtil;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * 飞书消息发送
 */
@Component
@Slf4j
public class LarkSendHelper {

    @Value("${system.env}")
    private String env;

    @Value("${alert.lark.url}")
    private String larkUrl;

    @Value("${alert.lark.keyword}")
    private String keyword;

    private static LarkSendHelper instance;

    public static LarkSendHelper getInstance() {
        return LarkSendHelper.instance;
    }

    @PostConstruct
    public void init() {
        setInstance(this);
    }

    private static void setInstance(LarkSendHelper instance) {
        LarkSendHelper.instance = instance;
    }


    public void sendMsg (String text) {

        JSONObject textJson = new JSONObject();
        textJson.put("text", keyword + "：" +text+",环境:"+env);


        JSONObject msgJson = new JSONObject();
        msgJson.put("content", textJson);
        msgJson.put("msg_type", "text");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(larkUrl);
        CloseableHttpResponse httpResponse = null;
        try {
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity se = new StringEntity(msgJson.toString(), "UTF-8");
            se.setContentType("text/json");
            httpPost.setEntity(se);
            httpResponse = httpClient.execute(httpPost);
        } catch (IOException e) {
            log.error("*ERROR* 飞书告警信息发送失败, 错误信息", e);
        } finally {
            if(httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("*ERROR* 飞书连接httpClient关闭异常, 错误信息", e);
                }
            }
            if(httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    log.error("*ERROR* 钉钉httpResponse关闭异常, 错误信息", e);
                }
            }
        }

    }




}
